import { memo } from 'react'
import styles from './index.module.scss'
import { useTitle } from 'ahooks'
import { Typography, Space, Form, Input, Button, message } from 'antd'
import { UserAddOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import { usenameRules, passwordRules, confirmRules } from '@/utils/constant'
import { Rule } from 'antd/es/form'
import { api_register } from '@/api'
import { useRequest } from 'ahooks'
import { useNavigate } from 'react-router-dom'

const { Title } = Typography

type registerType = {
  username: string
  nickname: string
  password: string
  confirm: string
}

const Register = memo(() => {
  useTitle('注册')
  const nav = useNavigate()

  const onFinish = (values: registerType) => {
    handleRegist(values)
  }

  const { run: handleRegist } = useRequest(
    async (values: registerType) => await api_register(values),
    {
      manual: true,
      onSuccess: () => {
        message.success('注册成功')
        nav('/login')
      },
    }
  )

  return (
    <div className={styles.container}>
      <div>
        <Space>
          <Title level={2}>
            <UserAddOutlined />
          </Title>
          <Title level={2}>注册新用户</Title>
        </Space>
      </div>
      <div>
        <Form onFinish={onFinish} validateTrigger="onBlur" style={{ minWidth: 300 }}>
          <Form.Item name="username" rules={usenameRules as Rule[]}>
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item name="nickname">
            <Input placeholder="请输入昵称" />
          </Form.Item>

          <Form.Item name="password" rules={passwordRules as Rule[]}>
            <Input.Password placeholder="请输入密码" />
          </Form.Item>

          <Form.Item
            dependencies={['password']}
            name="confirm"
            rules={[
              ...(confirmRules as Rule[]),
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次密码输入不一致'))
                },
              }),
            ]}
          >
            <Input.Password placeholder="请确认密码" />
          </Form.Item>

          <Form.Item style={{ textAlign: 'center' }}>
            <Space direction="vertical" style={{ textAlign: 'center', width: '100%' }}>
              <Button type="primary" htmlType="submit" block>
                注册
              </Button>
              <Link to="/login">已有账户，立即登录</Link>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
})

export default Register
